<?php

namespace User\Model;

use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;

class UserTable extends AbstractTableGateway {

	protected $table ='users';
	protected $tablename ='users';

	public function __construct(Adapter $adapter) {
		$this->adapter = $adapter;
		$this->resultSetPrototype = new ResultSet(new User);
		$this->initialize();
	}

	
	public function fetchAll()
	{
		$resultSet = $this->select();
		return $resultSet;
	}

	public function getUser($id)
	{
		$id = (int) $id;
		$rowset = $this->select(array('id_user' => $id));
		$row = $rowset->current();
		if (!$row) {
			throw new \Exception("Could not find row $id");
		}
		return $row;
	}

	public function getUserName($username)
	{
		//$username = (int) $username;
		$rowset = $this->select(array('username' => $username));
		$row = $rowset->current();
		if (!$row) {
			//throw new \Exception("Could not find $username ");
			return null;
		}
		return $row;
	}
	
	public function saveUser(User $user)
	{
		$data = array(

				'username' => $user->username,
				'id_personnel' => $user->id_personnel,
				'password' => $user->password,
				'email' => $user->email,
				'avatar' => $user->avatar,
				'isadmin' => $user->isadmin,
				'isblocked' => $user->isblocked,
				'signup_date' => $user->signup_date,
		);
		$id = (int)$user->id_user;
		if ($id == 0) {
			$this->insert($data);
		} else {
			if ($this->getUser($id)) {
				$this->update($data, array('id_user' => $id));
			} else {
				throw new \Exception('Form id does not exist');
			}
		}
	}

	public function addUser($username, $id_personnel,$password,$email,$avatar,$isadmin,$isblocked,$signup_date)
	{
		$data = array(
				'username' => $username,
				'id_personnel' => $id_personnel,
				'password' => $password,
				'email' => $email,
				'avatar' => $avatar,
				'isadmin' => $isadmin,
				'isblocked' => $isblocked,
				'signup_date' => $signup_date,
		);
		$this->insert($data);
	}

	public function updateUser($id, $username, $id_personnel,$password,$email,$avatar,$isadmin,$isblocked,$signup_date)
	{
		$data = array(
				'username' => $username,
				'id_personnel' => $id_personnel,
				'password' => $password,
				'email' => $email,
				'avatar' => $avatar,
				'isadmin' => $isadmin,
				'isblocked' => $isblocked,
				'signup_date' => $signup_date,
		);
		$this->update($data, array('id_user' => $id));
	}
	public function deleteAlbum($id)
	{
		$this->delete(array('id_user' => $id));
	}
}

?>
